package com.kanshu.ksgb.fastread.doudou.module.home.activity;

import android.Manifest;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.os.Process;
import android.provider.Settings;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.hz.yl.b.mian.XMain;
import com.inmobi.ads.InMobiNative;
import com.kanshu.ksgb.fastread.doudou.BuildConfig;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdStyleBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.AdUtils;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.SplashAdListener;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigBean;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.retrofit.ADConfigs;
import com.kanshu.ksgb.fastread.doudou.common.business.ad.toutiao.WeakHandler;
import com.kanshu.ksgb.fastread.doudou.common.business.manager.MMKVDefaultManager;
import com.kanshu.ksgb.fastread.doudou.common.business.routerservice.ConfigService;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ARouterUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.NetUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.OSUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.PermissionHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.ss.android.common.applog.TeaAgent;
import com.ss.android.common.applog.TeaConfigBuilder;
import com.umeng.analytics.MobclickAgent;
import com.wcl.notchfit.NotchFit;
import com.wcl.notchfit.args.NotchProperty;
import com.wcl.notchfit.args.NotchScreenType;
import com.wcl.notchfit.core.OnNotchCallBack;

import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import io.reactivex.android.schedulers.AndroidSchedulers;


public class AdSplashActivity extends Activity implements SplashAdListener, WeakHandler.IHandler {
    public static int ACTION_DESTORY = 9;
    public static final String SPLASH_KEY = "dynamic";
    @BindView(R.id.app_logo)
    ImageView appLogo;
    private ViewGroup adContainer;
    private TextView skipView;
    private ImageView splashHolder;
    public boolean canJump = false;
    private Timer mTimer;
    private PermissionHelper mPermissionHelper;
    public static final int READ_PHONE_STATE_CODE = 0x12;
    public static final int WRITE_EXTERNAL_STORAGE_CODE = 0x13;
    public static final int ACCESS_FINE_LOCATION_CODE = 0x14;
    public static final String CHANNEL_LOGO_NAME = "channel_logo_url.png";
    InMobiNative mInMobiSplash;
    private boolean isShowSkip = false;
    private WeakHandler mHandler = new WeakHandler(this);
    private static final int AD_TIME_OUT = 2500;
    private static final int MSG_GO_MAIN = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (getWindow() != null && getWindow().getDecorView() != null) {
            getWindow().getDecorView().setTag(ARouterConfig.PageTagParams.SPLASH_PAGE);
        }
        super.onCreate(savedInstanceState);
        if (!isTaskRoot()) {
            finish();
            return;
        }
        TTSdkInit();
        setContentView(R.layout.activity_start_layout);
        ButterKnife.bind(this);
        adContainer = findViewById(R.id.splash_container);
        skipView = findViewById(R.id.skip_view);
        splashHolder = findViewById(R.id.splash_holder);
//        int resource = getPartnerImgResource();
//        if (resource != 0) {
//            appLogo.setImageResource(resource);
//        } else {
//            appLogo.setImageResource(R.mipmap.ic_splash_logo);
//        }
        setPartenerImage();
        try {
            RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) appLogo.getLayoutParams();
            params.height = getResources().getDimensionPixelSize(R.dimen.px_355);
            appLogo.setLayoutParams(params);
        } catch (Exception e) {
            e.printStackTrace();
        }
        getPermissions();
        skipView.setOnClickListener(v -> doJump());
        chechNotch();
    }

    /**
     * 初始化广告信息
     */
    private void initAd() {
        if (!NetUtils.isNetworkAvailable(this)) {
            noAdDoJump();
            return;
        }
        //判断是否获取UserId
        if (!TextUtils.isEmpty(UserUtils.getUserId())) {
            //获取广告的后台配置
            ADConfigs.updateAdConfig();
            ADConfigBean config = ADConfigs.showAD(String.valueOf(ADConfigBean.POSITION_SPLASH));
            if (config == null) {
                noAdDoJump();
            } else {
                AdUtils.fetchAdUtil(AdSplashActivity.this, adContainer, skipView, ADConfigBean.POSITION_SPLASH, AdStyleBean.SPLASH_STYLE, 0, AdSplashActivity.this);
            }
        } else {
            noAdDoJump();
        }
    }

    /**
     * 头条⾏为数据上报SDK初始化
     */
    private void TTSdkInit() {
        if (getPackageName().equals(Utils.getProcessName(Xutils.getContext(), Process.myPid()))) {
            Log.i("", "");
            TeaAgent.init(TeaConfigBuilder.create(Xutils.getContext())
                    .setAid(Integer.parseInt(getString(R.string.toutiao_app_id)))
                    .setAppName(getString(R.string.toutiao_app_name))
                    .setChannel(UserUtils.getChannelId())
                    .createTeaConfig());
            TeaAgent.setDebug(true);
            String id = UserUtils.getUserId();
            if (!TextUtils.isEmpty(id)) {
                TeaAgent.setUserUniqueID(id);
            }
        }
    }

    private void noAdDoJump() {
        if (mHandler != null) {
            mHandler.sendEmptyMessageDelayed(MSG_GO_MAIN, AD_TIME_OUT);
        }
    }

    private void doJump() {
        getDynamicOperInfo();
    }

    private void getDynamicOperInfo() {
        startMainActivity(AdSplashActivity.this);
        overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
        finish();
    }

    /**
     * 跳转至主页
     *
     * @param context
     */
    public static void startMainActivity(Context context) {
        ARouterUtils.toActivity(ARouterConfig.HOME_PAGE);
//        Map<String, String> map = new HashMap<>();
//        StringBuilder sb = new StringBuilder();
//        sb.append(context.getString(R.string.base_jump_url))
//                .append(context.getString(R.string.main));
//        UrlRouter.from(context).jump(Utils.linkUrl(sb.toString(), map));
    }

    @Override
    protected void onResume() {
        super.onResume();
        JPushInterface.onResume(this);
        MobclickAgent.onResume(this);
        MobclickAgent.onPageStart(getClass().getSimpleName());
        if (canJump) {
            next();
        }
        canJump = true;
    }

    @Override
    protected void onPause() {
        super.onPause();
        canJump = false;
        JPushInterface.onPause(this);
        MobclickAgent.onPause(this);
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }

    @Override
    public void onBackPressed() {
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        adContainer = null;
        skipView = null;
        if (mTimer != null) {
            mTimer.cancel();
        }
        if (mInMobiSplash != null) {
            mInMobiSplash.destroy();
            mInMobiSplash = null;
        }
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
            mHandler = null;
        }
    }

    long mFirstGDTFinished = 0L;

    @Override
    public void onADTick(long millisUntilFinished) {
        skipView.setText(String.format(getString(R.string.ad_click_to_skip), Math.round(millisUntilFinished / 1000f)));
        //广点通开屏一秒钟后才可以点击跳过
        if (mFirstGDTFinished == 0) {
            mFirstGDTFinished = millisUntilFinished;
        } else {
            if (mFirstGDTFinished - millisUntilFinished > 800) {
                skipView.setEnabled(true);
            }
        }
    }

    @Override
    public void onFastADClosed(@NotNull Timer timer) {
        this.mTimer = timer;
    }

    @Override
    public void onAdLoadSucceeded(@Nullable View view) {
        splashHolder.setVisibility(View.INVISIBLE); // 广告展示后一定要把预设的开屏图片隐藏起来
    }

    @Override
    public void onSplashHolder(boolean isShow) {
        if (isShow) {
            splashHolder.setVisibility(View.VISIBLE);
        } else {
            splashHolder.setVisibility(View.GONE);
        }
    }

    @Override
    public void isShowSkipView(boolean isShow) {
    }

    @Override
    public void onAdLoadFailed() {
        doJump();
    }

    @Override
    public void onAdClicked() {
    }

    @Override
    public void onADClosed() {
        next();
    }

    @Override
    public void onBackAd(@NotNull Object ad) {
        if (ad instanceof InMobiNative) {
            mInMobiSplash = (InMobiNative) ad;
        }
    }

    @Override
    public void onJump(boolean jump) {
        // 头条广告避免返回Splash界面不跳转,延时处理
        AndroidSchedulers.mainThread().scheduleDirect(() -> {
            canJump = jump;
        }, 500, TimeUnit.MILLISECONDS);

    }

    private void next() {
        if (canJump) {
            doJump();
        } else {
            canJump = true;
        }
    }

    /**
     * 获取合作伙伴的图片资源id
     *
     * @return
     */
    public int getPartnerImgResource() {
        String imageName = BuildConfig.PARTNER_LOGO;
        if (!TextUtils.isEmpty(imageName)
                && (imageName.contains(".png") || imageName.contains(".jpg"))) {
            int index = imageName.lastIndexOf(".png");
            if (index == -1) {
                index = imageName.lastIndexOf(".jpg");
            }
            if (index > -1) {
                imageName = imageName.substring(0, index);
                return getResources().getIdentifier(imageName, "mipmap", getPackageName());
            }
        }
        return 0;
    }

    private void setPartenerImage() {
        InputStream is = null;
        try {
            is = getAssets().open(CHANNEL_LOGO_NAME);
            appLogo.setImageBitmap(BitmapFactory.decodeStream(is));
        } catch (Exception e) {
            appLogo.setImageResource(R.mipmap.ic_splash_logo);
            e.printStackTrace();
        } finally {
            if (is != null) {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void initData() {
        //洛米初始化  广告商要求进入app初始化
        XMain.getInstance().setAppKey(Xutils.getContext().getApplicationContext(), getString(R.string.ad_luomi_app_key));
        initAd();
        // 根据设备注册id
        ARouter.getInstance().navigation(ConfigService.class).registerIdByDevice();
    }

    private void getPermissions() {
        if (Build.VERSION.SDK_INT < 23) {
            initData();
            return;
        }
        mPermissionHelper = new PermissionHelper(this);
        mPermissionHelper.setPermissionModels(new PermissionHelper.PermissionModel[]{
                new PermissionHelper.PermissionModel("电话",
                        Manifest.permission.READ_PHONE_STATE, "我们需要读取手机信息的权限来标识您的身份", READ_PHONE_STATE_CODE),
                new PermissionHelper.PermissionModel("存储空间",
                        Manifest.permission.WRITE_EXTERNAL_STORAGE, "我们需要您允许我们读写你的存储卡，以方便我们临时保存一些数据", WRITE_EXTERNAL_STORAGE_CODE),
                new PermissionHelper.PermissionModel("定位",
                        Manifest.permission.ACCESS_FINE_LOCATION, "允许获取手机的定位权限，才可以正常的打开应用", ACCESS_FINE_LOCATION_CODE)
        });
        mPermissionHelper.setOnApplyPermissionListener(new PermissionHelper.OnApplyPermissionListener() {
            @Override
            public void onAfterApplyAllPermission() {
                if (OSUtils.isMIUI()) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                        if (!OSUtils.isMIUReadPhoneStateAuthorized(AdSplashActivity.this)) {
                            new AlertDialog.Builder(AdSplashActivity.this).setMessage("打开应用程序需要电话、定位和存储空间权限，方便标识身份和存储用戶数据，请进入设置页面授予权限。").setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                    Intent intent = new Intent();
                                    intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                                    //设置去向意图
                                    Uri uri = Uri.fromParts("package", AdSplashActivity.this.getPackageName(), null);
                                    intent.setData(uri);
                                    try {
                                        startActivityForResult(intent, 0);
                                    } catch (ActivityNotFoundException e) {
                                        finish();
                                    }
                                }
                            }).setNegativeButton("取消", (dialog, which) -> finish()).show();
                            return;
                        }
                    }
                }
                initData();
            }

            @Override
            public void onApplyOnPermission(int requestCode) {
            }
        });
        mPermissionHelper.applyPermissions();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        mPermissionHelper.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mPermissionHelper.onActivityResult(requestCode, resultCode, data);
    }

    @Override
    public void handleMsg(Message msg) {
        if (msg.what == MSG_GO_MAIN) {
            doJump();
        }
    }

    private void chechNotch() {
        NotchFit.fit(this, NotchScreenType.CUSTOM, new OnNotchCallBack() {
            @Override
            public void onNotchReady(NotchProperty notchProperty) {
                if (notchProperty.isNotchEnable()) {
                    MMKVDefaultManager.getInstance().setNotchHeight(notchProperty.getNotchHeight());
                }else{
                    MMKVDefaultManager.getInstance().setNotchHeight(0);
                }
            }
        });
    }
}